﻿using Api.Application.Command.Role;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using Yitter.IdGenerator;

namespace Api.Application.Handler.Role
{
    public class UpdateRoleHandler : IRequestHandler<UpdateRoleCommand, ApiResult<int>>
    {
        private readonly IBase<RoleModel> roleRepo;
        private readonly IMapper mapper;

        public UpdateRoleHandler(IBase<RoleModel> roleRepo,IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            
            var role= roleRepo.GetAll().Where(x => x.RoleName == request.RoleName).FirstOrDefault();
            var model = roleRepo.GetAll().Where(x => x.RoleName == request.RoleName && x.Id != request.Id && !x.IsDeleted).Count();
            if (model ==1)
            {
                result.Msg = "角色名已存在";
                result.Code = ApiEnum.Fail;
                return Task.FromResult(result);
            }
            role = mapper.Map(request, role);
            role.CrearName = "张三";
            role.UpdateName = "李四";
            role.UpdateTime = DateTime.Now;
            var r = roleRepo.Update(role).Result;
            if (r > 0)
            {
                result.Msg = "修改角色成功";
                result.Code = ApiEnum.OK;
                result.Data = r;
            }
            else
            {
                result.Msg = "修改角色失败";
                result.Code = ApiEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
